import datetime

from flask import jsonify, request, session

from pojo.Note import Note
from pojo.Note import mysql, Collect_by ,Like_by


def create_note():
    user_id = request.json.get('user_id')
    isbn = request.json.get('isbn')
    title = request.json.get('title')
    content = request.json.get('content')
    publish_date = request.json.get('publish_date')
    if not all([user_id, isbn, title, content, publish_date]):
        return ({
            "status": 1,
            "message": "缺少必须字段"
        }), 400
    note = Note(
        user_id=user_id,
        isbn=isbn,
        title=title,
        content=content,
        publish_date=publish_date,
        like_count=0,
        collect_count=0,
        transmit_count=0
    )
    mysql.session.add(note)
    mysql.session.commit()
    return ({
        "status": 0,
        "message": "笔记创建成功",
        "data": note.note_id
    }), 200


def delete_note(note_id):
    if not note_id:
        return ({
            "status": 1,
            "message": "缺少必须字段"
        }), 400
    # 查询要删除的笔记
    note = Note.query.get(note_id)
    # 如果笔记不存在
    if not note:
        return ({
            "status": 1,
            "message": "找不到指定的笔记"
        }), 404
    # 删除笔记
    mysql.session.delete(note)
    mysql.session.commit()
    return ({
        "status": 0,
        "message": "笔记删除成功"
    }), 200


def update_note(note_id):
    title = request.json.get('title')
    content = request.json.get('content')
    publish_date = request.json.get('publish_date')

    if not all([note_id, title, content, publish_date]):
        return ({
            "status": 1,
            "message": "缺少必须字段"
        }), 400
    # 查询要更新的笔记
    note = Note.query.get(note_id)
    # 如果笔记不存在
    if not note:
        return ({
            "status": 1,
            "message": "找不到指定的笔记"
        }), 404
    # 更新笔记信息
    note.title = title
    note.content = content
    note.publish_date = publish_date
    mysql.session.commit()
    return ({
        "status": 0,
        "message": "笔记更新成功"
    }), 200


def get_note(note_id):
    if not note_id:
        return ({
            "status": 1,
            "message": "缺少必须字段"
        }), 400
    # 查询笔记
    note = Note.query.get(note_id)
    # 如果笔记不存在
    if not note:
        return ({
            "status": 1,
            "message": "未找到笔记"
        }), 404
    # 构建返回数据
    note_data = {
        "note_id": note.note_id,
        "user_id": note.user_id,
        "isbn": note.isbn,
        "title": note.title,
        "content": note.content,
        "publish_date": note.publish_date,
        "like_count": note.like_count,
        "collect_count": note.collect_count,
        "transmit_count": note.transmit_count
    }
    return ({
        "status": 0,
        "message": "找到笔记",
        "data": note_data
    }), 200

def get_notes(page_num,page_size,order_by,user_id,isbn,content_keyword):
    print(order_by)
    if page_num is None:
        return {'error': '缺少 page_num 参数'}, 400
    try:
        page_num = int(page_num)
    except ValueError:
        return {'error': 'page_num 参数必须是整数'}, 400

    if page_size is None:
        return {'error': '缺少 page_size 参数'}, 400
    try:
        page_size = int(page_size)
    except ValueError:
        return {'error': 'page_size 参数必须是整数'}, 400


    query = Note.query
    if user_id:
        query = query.filter(Note.user_id == user_id)
    if isbn:
        query = query.filter(Note.isbn == isbn)
    if content_keyword:
        query = query.filter(Note.content.like(f'%{content_keyword}%'))
    if order_by == "hot":
        query = query.order_by(Note.like_count.desc())
    elif order_by == "new":
        query = query.order_by(Note.publish_date.desc())

    note_list = query.paginate(page_num, page_size).items

    if not note_list:
        return ({
            "status": 1,
            "message": "获取失败：未找到笔记"
        }), 404

    total = query.count()
    return ({
        "status": 0,
        "message": "找到笔记",
        "data": {
            "total": total,
            "book_info": [note.serialize() for note in note_list]
        }
    }), 200

def note_like(note_id):
    user_id = request.json.get('user_id')
    if user_id is None:
        return {'status': 1, 'message': '缺少 user_id 参数'}, 400

    note = Note.query.get(note_id)
    if note is None:
        return {'status': 1, 'message': '未找到该笔记'}, 404

    like_entry = Like_by.query.filter_by(note_id=note_id, like_id=user_id).first()

    if like_entry:  # 如果用户已经点赞
        mysql.session.delete(like_entry)
        note.like_count -= 1
        mysql.session.commit()
        return {'status': 0, 'message': '取消点赞成功'}, 200
    else:  # 如果用户尚未点赞
        new_like_entry = Like_by(note_id=note_id, like_id=user_id)
        mysql.session.add(new_like_entry)
        note.like_count += 1
        mysql.session.commit()
        return {'status': 0, 'message': '点赞成功'}, 200

def note_collect(note_id):
    user_id = request.json.get('user_id')
    if user_id is None:
        return {'status': 1, 'message': '缺少 user_id 参数'}, 400

    note = Note.query.get(note_id)
    if note is None:
        return {'status': 1, 'message': '未找到该笔记'}, 404

    collect_entry = Collect_by.query.filter_by(note_id=note_id, collect_id=user_id).first()

    if collect_entry:  # 如果用户已经收藏
        mysql.session.delete(collect_entry)
        note.collect_count -= 1
        mysql.session.commit()
        return {'status': 0, 'message': '取消收藏成功'}, 200
    else:  # 如果用户尚未收藏
        new_collect_entry = Collect_by(note_id=note_id, collect_id=user_id)
        mysql.session.add(new_collect_entry)
        note.collect_count += 1
        mysql.session.commit()
        return {'status': 0, 'message': '收藏成功'}, 200

def note_transmit(note_id):
    note = Note.query.get(note_id)
    # 如果笔记不存在
    if not note:
        return ({
            "status": 1,
            "message": "找不到指定的笔记"
        }), 404
    note.transmit_count = note.transmit_count + 1
    mysql.session.commit()
    return ({
        "status": 0,
        "message": "修改转发状态成功"
    }), 200
